<?php

namespace Xrfg\Api\Trading\Spot\Resources;

use App\Http\Resources\Resource;
use Illuminate\Support\Facades\Auth;
use Xrfg\Core\Trading\Spot\Models\Order;
use Xrfg\Core\Trading\Spot\Models\Trade;

class TradesResource extends Resource
{
    public function toArray($request)
    {
        /* @var Order $this */
        return [
            'id' => $this->id,
            'created_at' => (string)$this->created_at,
            'type' => $this->getType(),
            'symbol' => $this->symbol,
            'side' => self::getSide(),
            'price' => $this->price,
            'number' => $this->number,
            'fee' => self::getFee(),
        ];
    }

    public function getSide()
    {
        /** @var Trade $this */
        if ($this->buy_user_id === $this->sell_user_id) {
            /* @var Trade $this */
            return $this->side;
        }
        /** @var Trade $this */
        if (Auth::id() === $this->buy_user_id) {
            return Trade::SIDE_BUY;
        } else {
            return Trade::SIDE_SELL;
        }
    }

    public function getFee()
    {
        if (Trade::SIDE_BUY == $this->getSide()) {
            /* @var Trade $this */
            return $this->buy_fee;
        } else {
            /* @var Trade $this */
            return $this->sell_fee;
        }
    }

    public function getType()
    {
        return Order::find(max($this->buy_order_id , $this->sell_order_id))->type;
    }
}
